<template>
  <div>
    <!-- 1.顶部栏 -->
    <van-nav-bar
      title="登录"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <!-- 2.登录布局 -->

    <van-form @submit="onSubmit">
      <van-field
        v-model="phone"
        name="mobile"
        label="手机号"
        placeholder="手机号"
        required
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不正确'
          }
        ]"
      />
      <van-field
        v-model="code"
        type="password"
        name="code"
        label="验证码"
        placeholder="验证码"
        required
        :rules="[
          { required: true, message: '请填写验证码' },
          {
            pattern: /\d{6}/,
            message: '验证码格式不正确'
          }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="登录中..."
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>
<script>
// 2.3 导入登录接口
import { userLogin } from './user.js'
// 2.4 导入token
import { saveToken } from '@/utils/token.js'
export default {
  name: 'login',
  data () {
    return {
      phone: '15512345678',
      code: '246810',
      isLoading: false
    }
  },
  methods: {
    //   2.1 vant中的Form表单自带验证功能rules。通过验证，才会触发onSubmit这个事件
    onSubmit (values) {
      // 2.2 values是对象，属性名是name的值，属性值是输入框内容
      console.log('submit', values)
      this.isLoading = true
      // values是解构赋值的写法
      userLogin(values)
        .then(res => {
          console.log(res)
          // Toast.success('登录成功')
          this.$toast.success('登录成功')
          // 登录成功，本地保存token。并跳转到首页
          saveToken(res.data.data)
          this.$router.push({ path: '/home' })
        })
        .catch(err => {
          console.log(err)
          // Toast.fail('登录失败')
          this.$toast.fail('登录失败')
        })
        .then(() => {
          this.isLoading = false
        })
    }
  }
}
</script>

<style lang="less" scoped>
// 注意：子组件有scoped，就要配合::v-deep一起使用css样式输出才有效！
::v-deep .van-nav-bar {
  background-color: #0098fa;
  .van-nav-bar__text {
    color: #fff;
  }
  .van-icon-arrow-left {
    color: #fff;
  }
  .van-nav-bar__title {
    color: #fff;
  }
}
</style>
